package com.example.springbooteasycode.zjrc.project.Koal.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpDataReceiver {
    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(6000)) {
            System.out.println("服务器启动，监听端口 6000...");

            while (true) {
                try (Socket socket = serverSocket.accept();
                     InputStream in = socket.getInputStream()) {

                    // 读取数据
                    byte[] buffer = new byte[4096];
                    int bytesRead = in.read(buffer);

                    if (bytesRead > 0) {
                        byte[] receivedData = new byte[bytesRead];
                        System.arraycopy(buffer, 0, receivedData, 0, bytesRead);

                        // 解析数据
                        parseCommand(receivedData);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void parseCommand(byte[] data) {
        // 解析指令长度（前2字节）
        int cmdLength = ((data[0] & 0xFF) << 8) | (data[1] & 0xFF);

        // 解析指令代码（接下来2字节）
        int cmdCode = ((data[2] & 0xFF) << 8) | (data[3] & 0xFF);

        // 解析交易模式（接下来4字节）
        long dealPattern = ((long) (data[4] & 0xFF) << 24) |
                ((long) (data[5] & 0xFF) << 16) |
                ((long) (data[6] & 0xFF) << 8) |
                (data[7] & 0xFF);

        // 解析剩余数据
        byte[] payload = new byte[data.length - 8];
        System.arraycopy(data, 8, payload, 0, payload.length);

        // 输出结果
        System.out.println("接收到数据:");
        System.out.println("指令长度: " + cmdLength);
        System.out.println("指令代码: 0x" + Integer.toHexString(cmdCode).toUpperCase());
        System.out.println("交易模式: " + dealPattern);
        System.out.println("负载数据: " + new String(payload));
    }
}
